﻿using UnityEngine;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace Hont.AStar
{
    public class HontAStarHelper
    {
        public static Position[] CombinePath(Position[] positionArr)
        {
            if (positionArr.Length < 2) return positionArr;

            var resultList = new HashSet<Position>();
            var mOptimizablePathList = new List<Position>();
            Position? lastDir = null;

            resultList.Add(positionArr.First());

            for (int i = 1; i < positionArr.Length; i++)
            {
                var x = positionArr[i - 1];
                var y = positionArr[i];
                var flag = true;

                var dir = new Position();

                dir.X = y.X - x.X;
                dir.Y = y.Y - x.Y;
                dir.Z = y.Z - x.Z;

                if (lastDir != null && (dir.X != lastDir.Value.X || dir.Y != lastDir.Value.Y || dir.Z != lastDir.Value.Z))
                    flag = false;
                
                mOptimizablePathList.Add(x);

                if (!flag)
                {
                    resultList.Add(mOptimizablePathList.LastOrDefault());
                    mOptimizablePathList.Clear();
                }

                lastDir = dir;
            }

            resultList.Add(positionArr.Last());

            return resultList.ToArray();
        }
    }
}
